package com.friendsystem.service;

import com.friendsystem.dao.FriendshipDao;
import com.friendsystem.dao.UserDao;
import com.friendsystem.hadoop.FriendRecommendationJob;
import com.friendsystem.model.User;
import org.apache.hadoop.mapreduce.Job;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FriendService {
    private FriendshipDao friendshipDao = new FriendshipDao();

    public List<User> getFriendRecommendations(String userId) throws IOException {
        List<User> recommendations = new ArrayList<>();

        try (UserDao userDao = new UserDao()) {
            // 1. 根据好友数量推荐(好友少的用户)
            recommendations.addAll(userDao.getUsersWithFewFriends(10));

            // 2. 随机推荐
            recommendations.addAll(userDao.getRandomUsers(5));

            // 3. 使用Hadoop MapReduce计算共同好友推荐
            FriendRecommendationJob job = new FriendRecommendationJob();
            Job hadoopJob = job.createRecommendationJob(userId);
            if (hadoopJob.waitForCompletion(true)) {
                recommendations.addAll(job.getRecommendationResults());
            }

            // 去重和过滤已经是好友的用户
            List<String> friendIds = friendshipDao.getFriendIds(userId);
            recommendations.removeIf(user ->
                    user.getUserId().equals(userId) || friendIds.contains(user.getUserId()));
        }

        return recommendations;
    }

    public void sendFriendRequest(String userId, String friendId) throws IOException {
        friendshipDao.createFriendship(userId, friendId, "pending");
    }

    public void acceptFriendRequest(String userId, String friendId) throws IOException {
        friendshipDao.updateFriendshipStatus(friendId, userId, "accepted");

        // 更新用户好友计数
        try (UserDao userDao = new UserDao()) {
            userDao.incrementFriendCount(userId);
            userDao.incrementFriendCount(friendId);
        }
    }

    public void rejectFriendRequest(String userId, String friendId) throws IOException {
        friendshipDao.updateFriendshipStatus(friendId, userId, "rejected");
    }
}